package dao

import (
	"errors"
	"gorm.io/gorm"
	"product-service/common"
	"product-service/dao/entity"
)

var (
	PmsAttrDao = &pmsAttrDao{}
)

type pmsAttrDao struct {
}

func (this *pmsAttrDao) FindById(db *gorm.DB, id int64) (*entity.PmsAttr, error) {
	model := &entity.PmsAttr{}
	db.Find(model, id)
	if model.AttrId == 0 {
		return nil, errors.New("无此用户")
	}
	return model, nil
}

func (this *pmsAttrDao) FindAll(db *gorm.DB, query *common.PageQuery) ([]*entity.PmsAttr, int64, error) {
	tx := db.Scopes(Page(int(query.Page), int(query.Size)))

	//把数据封装到any里
	var models []*entity.PmsAttr

	//直接拼接所有条件
	model := query.Model.(*entity.PmsAttr)

	//count不包含limit条件
	var count int64
	tx.Model(&model).Count(&count)
	newTx := tx.Where("attr_name like ?", "%"+model.AttrName+"%")
	//查询所有,不带分类的
	if model.CatelogId == 0 {
		err := newTx.Find(&models).Error
		if err != nil {
			return nil, 0, err
		}
	} else {
		err := newTx.Where("attr_type=?", model.AttrType).
			Where("catelog_id=?", model.CatelogId).
			Find(&models).Error
		if err != nil {
			return nil, 0, err
		}
	}
	return models, count, nil
}

func (this *pmsAttrDao) DeleteById(db *gorm.DB, id int64) error {
	tx := db.Delete(&entity.PmsAttr{}, id)
	if tx.Error != nil {
		return errors.New("无效删除")
	}
	return nil
}
func (this *pmsAttrDao) UpdateById(db *gorm.DB, id int64, model *entity.PmsAttr) error {
	model.AttrId = id
	tx := db.Updates(model)
	if tx.Error != nil {
		return errors.New("无效更新")
	}
	return nil
}

func (this *pmsAttrDao) Save(db *gorm.DB, model *entity.PmsAttr) (*entity.PmsAttr, error) {
	tx := db.Create(model)
	if tx.RowsAffected == 0 {
		return nil, errors.New("保存失败")
	}
	return model, nil
}
